#include "CIniFile.h"
#include <iostream>
using namespace std;

#define MAXVALLEN 128
#define MAXNODELEN 128
#define MAXALLNODES 1024
#define MAXALLKEYS MAXALLNODES

void CIniFile::SetFileName(const CString &pathname)
{
    fpathname=pathname;
    return;
}

CString CIniFile::GetFileName(void)
{
    return fpathname;
}

bool CIniFile::SetValue(const CString &node, const CString &key,const CString &val, bool bCreate)
{
    return WritePrivateProfileString(node,key,val,fpathname);
}

bool CIniFile::GetValue(const CString &node, const CString &key,CString & val )
{
    return GetPrivateProfileString(node, key, "", val.GetBuffer(MAXVALLEN),MAXVALLEN,fpathname);
}

bool CIniFile::DelNode(const CString &node)
{
    return WritePrivateProfileString(node, NULL, NULL, fpathname);
}

bool CIniFile::DelKey(const CString &node,const CString key)
{
    return WritePrivateProfileString(node, key, NULL, fpathname);
}

int  CIniFile::GetNodes(CStringArray &nodes)
{
    char nodesstr[MAXALLNODES];
    char str_tmp[MAXNODELEN];
    int i;
    char *node_tmp;
    
    memset( nodesstr, 0x00, sizeof(nodesstr) );
    if(!GetPrivateProfileSectionNames(nodesstr,MAXALLNODES,fpathname))
        return -1;
    return Str2Array(nodesstr,nodes);
}

int  CIniFile::GetKeys(const CString &node,KeyVal &kv)
{
    char all_keys[MAXALLKEYS];
    CStringArray vals;
    memset( all_keys, 0x00, sizeof(all_keys) );
    if(!GetPrivateProfileSection( node, all_keys, MAXALLKEYS, fpathname ))
        return -1;
    Str2Array(all_keys,vals);
    return Array2KeyVal( vals, kv );
}

bool CIniFile::DelAllNodes()
{
    CStringArray nodes;
    int i,nNode;

    nNode=GetNodes(nodes);
    for( i=0; i<nNode; i++ )
    {
        if(!DelNode(nodes[i]))
            return false;
    }
    return true;
}

int CIniFile::Str2Array(char * const str,CStringArray &arr)
{
    int i;
    char tmp_str[128];
    char *p;

    p = str;
    for( i=0; i<MAXALLNODES; i++ )
    {
        memset( tmp_str, 0x00, sizeof(tmp_str) );
        if( str[i] == 0 )
        {
            strncpy( tmp_str, p, str+i-p );
            arr.Add( tmp_str );
            p=str+i;
            if( *(++p) == 0 )
                break;
        }
    }
    return (int)arr.GetSize();
}

int CIniFile::Array2KeyVal(const CStringArray & arr,KeyVal & kv)
{
    int i;
    char tmp[MAXVALLEN], key[MAXVALLEN];
    char val[MAXVALLEN];
    char *pos;
   
    memset( val, 0x00, sizeof(val) );
    memset( key, 0x00, sizeof(key) );

    for( i=0; i<arr.GetSize();i++ )
    {
       memset( tmp, 0x00, sizeof(tmp) );
       strcpy( tmp, arr[i] );
       pos = (char *)strchr( tmp, '=' );
       strncpy( key, tmp, pos-tmp );
       strcpy( val, pos+1 );
       kv.insert( KeyVal::value_type(key,val) );
    }
    return kv.size();
}